import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:gameplay_flutter/lib_baseview/theme/jr.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:gameplay_flutter/m_discover/sel_friend/sel_friend_view.dart';
import 'package:get/get.dart';
import 'package:ones/ui.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../generated/assets.dart';
import '../../resource/language/generated/l10n.dart';
import 'post_logic.dart';

class PostPage extends StatelessWidget {
  PostPage({Key? key}) : super(key: key);

  final PostLogic logic = Get.put(PostLogic());

  @override
  Widget build(BuildContext context) {
    TextDirection currentDirection = Directionality.of(context);
    bool isRTL = currentDirection == TextDirection.rtl;

    return WillPopScope(
      onWillPop: () async {
        if (EasyLoading.isShow) {
          return false;
        }
        return true;
      },
      child: Obx(() {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Stack(children: [
            Container(height: 132).linearGradientColor([Color(0xffDCD4FF), Colors.white],
                begin: Alignment.topCenter, end: Alignment.bottomCenter),
            SafeArea(
              child: Row(
                children: [
                  Image.asset(Assets.discoverClose, width: 18, height: 18).paddingAll(11).onClick(() {
                    Get.back();
                  }),
                  Spacer(),
                  Opacity(
                    opacity: logic.sendEnable() ? 1 : 0.4,
                    child: Row(
                      children: [
                        Image.asset(Assets.discoverPost, width: 18, height: 18).marginRight(4),
                        Text(T.current.discover4_post).fontSize(16).colorInt(0xffffffff).fontWeight(FontWeight.w600),
                      ],
                    )
                        .paddingSymmetric(horizontal: 15, vertical: 7)
                        .backgroundColorInt(0xff8A72FE)
                        .roundedRect(90)
                        .onClick(
                      () {
                        Debouncer.run("post_moment", 400.milliseconds, () {
                          logic.discoverSaveDynamic();
                        });
                      },
                    ),
                  ),
                ],
              ).paddingOnly(left: 5, right: 16, top: 10, bottom: 10),
            ),
            SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 12),
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: [
                      ...logic.selectedAssets.map(
                        (element) {
                          return Stack(
                            children: [
                              AssetEntityImage(element, fit: BoxFit.cover, isOriginal: false, width: 72, height: 72)
                                  .roundedRect(8)
                                  .marginRight(8),
                              JR.img(Assets.discoverGrayCircleClose, width: 18, height: 18).onClick(() {
                                logic.selectedAssets.remove(element);
                                logic.sendEnable(logic.selectedAssets.isNotEmpty);
                                logic.selectedAssets.refresh();
                              }).positioned(right: 0, top: 0),
                            ],
                          );
                        },
                      ),
                      Visibility(
                        visible:
                            !(logic.selectedAssets.isNotEmpty && logic.selectedAssets.first.type == AssetType.video ||
                                (logic.selectedAssets.length >= 9)),
                        child: Center(
                          child: Image.asset(Assets.discoverPlus, width: 14, height: 14),
                        ).backgroundColorInt(0xffF2F2F2).size(width: 72, height: 72).roundedRect(8).onClick(
                          () {
                            logic.selAssets();
                          },
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 16),
                  TextField(
                    controller: logic.titleController,
                    maxLength: 40,
                    decoration: InputDecoration(
                      counterText: '',
                    ),
                  )
                      .noBorder()
                      .hint(T.current.discover5_my_title)
                      .hintColor(Color(0xffC1C1C1))
                      .hintSize(20)
                      .fontSize(20),
                  // SizedBox(height: 8),
                  Container(height: 0.5, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 1),
                  Directionality(
                    textDirection: isRTL ? TextDirection.rtl : TextDirection.ltr,
                    child: TextField(
                      maxLines: null,
                      textDirection: TextDirection.ltr,
                      textAlign: isRTL ? TextAlign.end : TextAlign.start,
                      keyboardType: TextInputType.text,
                      controller: logic.contentController,
                      style: const TextStyle(fontSize: 16),
                      onChanged: (value) {
                        if (value.isNotEmpty && value.length > logic.previewText.length && value.endsWith(' @')) {
                          logic.atUser(context);
                        }
                        logic.previewText = value;
                      },
                      decoration: InputDecoration(
                        hintText: T.current.discover5_maincontent,
                        hintStyle: const TextStyle(color: Color(0xffC1C1C1), fontSize: 16),
                        hintTextDirection: TextDirection.ltr,
                        border: InputBorder.none,
                      ),
                    ).height(150),
                  ),
                  Row(
                    children: [
                      Text(T.current.discover5_friends)
                          .fontSize(12)
                          .colorInt(0xff8A72FE)
                          .paddingSymmetric(horizontal: 12, vertical: 3)
                          .backgroundColorInt(0xffF8F1FF)
                          .roundedRect(36)
                          .onClick(() {
                        logic.atUser(context);
                      }).marginRight(8),
                      // Row(
                      //   children: [
                      //     ...logic.topics.map(
                      //       (element) {
                      //         return Text("#${element.name}")
                      //             .fontSize(12)
                      //             .colorInt(0xff8A72FE)
                      //             .paddingSymmetric(horizontal: 12, vertical: 3)
                      //             .backgroundColorInt(0xffF8F1FF)
                      //             .roundedRect(36)
                      //             .onClick(
                      //           () {
                      //             logic.selTopic(element);
                      //           },
                      //         ).marginRight(8);
                      //       },
                      //     ),
                      //   ],
                      // ).scrollable(direction: Axis.horizontal).expanded(),
                    ],
                  ).marginBottom(20),
                  Container(height: 0.5, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 16),
                  Row(
                    children: [
                      Image.asset(Assets.discoverLocation, width: 16, height: 16).marginRight(5),
                      Text(T.current.discover4_add_location).fontSize(16),
                      Spacer(),
                      Text(logic.getCityName(logic.address())).colorInt(0xff666666).fontSize(16),
                      SizedBox(width: 4),
                      JR.img(Assets.discoverArrow, width: 14, height: 20),
                    ],
                  ).backgroundColor(Colors.white).onClick(() {
                    logic.addLocation();
                  }),
                  Container(height: 0.5, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 16),
                  Row(
                    children: [
                      Image.asset(Assets.discoverLock, width: 16, height: 16).marginRight(5),
                      Text(T.current.discover_share_with).fontSize(16),
                      Spacer(),
                      Text(logic.getPermissionString()).colorInt(0xff666666).fontSize(16),
                      SizedBox(width: 4),
                      JR.img(Assets.discoverArrow, width: 14, height: 20),
                    ],
                  ).onClick(() {
                    // showCommentGiftBottomSheet();
                    showLockBottomSheet();
                  }),
                  Container(height: 0.5, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 16),
                ],
              ).paddingSymmetric(horizontal: 16).marginTop(60),
            ),
          ]),
        );
      }),
    );
  }

  showLockBottomSheet() async {
    return Get.bottomSheet(
      Column(
        children: [
          SizedBox(height: 26),
          Column(
            children: [
              Text(T.current.discover5_public).fontSize(18).color(Colors.black).marginBottom(2),
              Text(T.current.discover5_visible_to_everyone).fontSize(12).color(Color(0xffD8D8D8)),
            ],
          ).backgroundColor(Colors.transparent).onClick(
            () {
              logic.permission(3);
              Get.back();
            },
          ),
          Container(height: 1, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 8),
          Column(
            children: [
              Text(T.current.discover5_only_homepage).fontSize(18).color(Colors.black).marginBottom(2),
              Text(T.current.discover9_see_homeoage).fontSize(12).color(Color(0xffD8D8D8)),
            ],
          ).backgroundColor(Colors.transparent).onClick(
            () {
              logic.permission(2);
              Get.back();
            },
          ),
          Container(height: 1, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 8),
          Column(
            children: [
              Text(T.current.c_friend).fontSize(18).color(Colors.black).marginBottom(2),
              Text(T.current.discover9_huxiang_guanzhu).fontSize(12).color(Color(0xffD8D8D8)),
            ],
          ).backgroundColor(Colors.transparent).onClick(
            () {
              logic.permission(4);
              Get.back();
            },
          ),
          Container(height: 1, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 8),
          Column(
            children: [
              Text(T.current.discover5_private_status).fontSize(18).color(Colors.black).marginBottom(2),
              Text(T.current.discover9_see_oneself).fontSize(12).color(Color(0xffD8D8D8)),
            ],
          ).backgroundColor(Colors.transparent).onClick(
            () {
              logic.permission(1);
              Get.back();
            },
          ),
          Container(height: 1, color: Color(0xffF2F2F2)).marginSymmetric(vertical: 8),
          Text(T.current.chat3_cancel).colorInt(0xffA8A8A8).fontSize(22).marginSymmetric(vertical: 8).onClick(() {
            Get.back();
          }),
        ],
      ).backgroundColor(Colors.white).roundedRectVertical(12, 0).height(360),
    );
  }
}

class ImageTabIndicator extends Decoration {
  final ImageProvider image; // 图片资源（AssetImage/NetworkImage）
  final double width; // 指示器宽度
  final double height; // 指示器高度

  const ImageTabIndicator({
    required this.image,
    this.width = 24,
    this.height = 24,
  });

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _ImagePainter(image, width, height);
  }
}

class _ImagePainter extends BoxPainter {
  final ImageProvider image;
  final double width;
  final double height;

  _ImagePainter(this.image, this.width, this.height);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final imageStream = image.resolve(ImageConfiguration.empty);
    imageStream.addListener(ImageStreamListener((ImageInfo info, bool _) {
      try {
        final image = info.image;
        // 计算图片绘制位置（居中）
        final rect = offset & configuration.size!;
        final imageOffset = Offset(
          rect.center.dx - width / 2,
          rect.bottom - height,
        );
        // 绘制图片
        canvas.drawImageRect(
          image,
          Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
          Rect.fromLTWH(imageOffset.dx, imageOffset.dy, width, height),
          Paint(),
        );
      } catch (e) {}
    }));
  }
}
